package com.tencent.wxcloudrun.service.impl;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencent.wxcloudrun.domain.TUserCardApply;
import com.tencent.wxcloudrun.enums.CardApplyStatEnum;
import com.tencent.wxcloudrun.exception.BusinessException;
import com.tencent.wxcloudrun.mapper.TUserCardApplyMapper;
import com.tencent.wxcloudrun.service.TUserCardApplyService;
import com.tencent.wxcloudrun.vo.request.card.StoreCardApproveApplyReqVo;

import lombok.extern.slf4j.Slf4j;

/**
 * @author ziyin.zhao
 * @description 针对表【t_user_card_apply(用户卡片记录表)】的数据库操作Service实现
 * @createDate 2025-05-13 09:21:26
 */
@Slf4j
@Service
public class TUserCardApplyServiceImpl extends ServiceImpl<TUserCardApplyMapper, TUserCardApply>
    implements TUserCardApplyService {

    @Override
    public void cancelApply(Long userCardApplyId) {
        TUserCardApply apply = this.getById(userCardApplyId);
        if (Objects.nonNull(apply)) {
            apply.setStatus(CardApplyStatEnum.CANCEL.getValue());
            apply.setUpdatedTime(LocalDateTime.now());
            this.updateById(apply);
        }
    }

    @Override
    public TUserCardApply approveApply(Long userId, StoreCardApproveApplyReqVo reqVo) {
        TUserCardApply apply = this.getById(reqVo.getUserCardApplyId());
        if (Objects.nonNull(apply)) {
            if (apply.getStatus() != CardApplyStatEnum.TO_APPROVE.getValue()) {
                log.error("卡片审批-当前申请状态已审批或已取消-状态={}", apply.getStatus());
                throw new BusinessException("当前申请状态已审批或已取消");
            }
            apply.setStatus(reqVo.getApplyStatus());
            apply.setReason(reqVo.getReason());
            apply.setUpdatedBy(String.valueOf(reqVo.getUserId()));
            apply.setUpdatedTime(LocalDateTime.now());
            this.updateById(apply);
        }
        return apply;
    }

    @Override
    public Page<TUserCardApply> listApply(Page<TUserCardApply> page, Long userId, Integer status) {
        LambdaQueryWrapper<TUserCardApply> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(status != null && status != -1, TUserCardApply::getStatus, status);
        queryWrapper.eq(userId != null, TUserCardApply::getUserId, userId);
        queryWrapper.eq(TUserCardApply::getEnableFlag, 1);
        queryWrapper.orderByDesc(TUserCardApply::getCreatedTime);
        return this.page(page, queryWrapper);
    }
}
